package cn.itsource.ymcc.service.impl;

import cn.itsource.ymcc.constant.RConst;
import cn.itsource.ymcc.domain.Login;
import cn.itsource.ymcc.exception.GlobalException;
import cn.itsource.ymcc.mapper.LoginMapper;
import cn.itsource.ymcc.result.JsonResult;
import cn.itsource.ymcc.service.ILoginService;
import cn.itsource.ymcc.util.AssertUtil;
import cn.itsource.ymcc.util.jwtutil.JwtUtils;
import cn.itsource.ymcc.util.jwtutil.PayloadData;
import cn.itsource.ymcc.vo.LoginVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 登录表 服务实现类
 * </p>
 *
 * @author Mr.xiang
 * @since 2023-09-30
 */
@Service
public class LoginServiceImpl extends ServiceImpl<LoginMapper, Login> implements ILoginService {

    private final static Integer EXPIRE = 24 * 60 * 60;
    @Override
    public JsonResult accountLogin(LoginVo loginVo) {
        //判断用户名是否正确
        Login login = baseMapper.selectOne(new LambdaQueryWrapper<Login>()
                .eq(Login::getUsername, loginVo.getUsername())
                .eq(Login::getType, loginVo.getType()));
        AssertUtil.isNotNull(login, "用户名或密码错误！");

        //用户名正确再校验密码
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        boolean matches = bCryptPasswordEncoder.matches(loginVo.getPassword(), login.getPassword());
        AssertUtil.isTrue(matches,"用户名或密码错误！");

        Map<String, Object> hashMap = new HashMap<>();
        //使用jwt生成token
        PayloadData payloadData = new PayloadData();
        payloadData.setLogin(login);

        if (login.getType() == RConst.Num.INT_0){
            //0代表管理员
            login.setPassword("");
            payloadData.setAdmin(login);
            hashMap.put("admin",login);
        }else {
            login.setPassword("");
            payloadData.setUser(login);
            hashMap.put("user",login);
        }

        String token = JwtUtils.getToken(payloadData, EXPIRE);
        hashMap.put("token",token);
        return JsonResult.success().setData(hashMap);
    }
}
